<template>
  <div class="age-limit-list">
    <div class="age-limit-item" v-for="(item, index) in valueVModel" :key="index">
      <SafeInputNumber
        :disabled="disabled"
        v-model="item[filed.start]"
        clearable
        :precision="0"
        :min="0"
        :max="999"
        :placeholder="startPlaceholder"
      />
      <span class="separator">到</span>
      <SafeInputNumber
        v-model="item[filed.end]"
        :disabled="disabled"
        clearable
        :precision="0"
        :min="0"
        :max="999"
        :placeholder="endPlaceholder"
      />
      <el-button :disabled="disabled" icon="el-icon-delete" style="margin-left: 5px;" type="danger" @click="onDeleteItem(index)"></el-button>
    </div>
    <el-button :disabled="disabled" style="width: 100%" size="mini" icon="el-icon-circle-plus-outline" @click="onAddItem">新增</el-button>
  </div>
</template>

<script>
export default {
  name: 'AgeLimit',
  props: {
    // 分割符
    separator: {
      type: String,
      default: '到'
    },
    // 开始提示内容
    startPlaceholder: {
      type: String,
      default: '开始年龄'
    },
    // 结束提示内容
    endPlaceholder: {
      type: String,
      default: '结束年龄'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    filed: {
      type: Object,
      default: () => ({
        start: 'min',
        end: 'max'
      })
    },
    // 最大条数限制
    limit: {
      type: Number,
      default: 10
    },
    value: {
      type: Array,
      default: () => []
    }
  },
  computed: {
    valueVModel: {
      get () {
        return this.value ?? []
      },
      set (val) {
        this.$emit('input', val)
      }
    }
  },
  methods: {
    // 方法 - 校验
    validate (where) {
      const info = { valid: true, msg: '' }

      info.valid = this.valueVModel.every(item => {
        if (this.$isEmpty(item.min) || this.$isEmpty(item.max)) {
          info.msg =  where ? `${where}：请填写完整年龄信息` : '请填写完整年龄信息'
          return false
        }

        if (parseFloat(item.max) <= parseFloat(item.min)) {
          info.msg = where ? `${where}：结束年龄不得大于开始年龄` : '结束年龄不得大于开始年龄'
          return false
        }

        return true
      })

      return info
    },

    // 事件 - 添加条目
    onAddItem () {
      if (this.valueVModel.length >= this.limit) {
        this.$swal.warning(`最多限制添加行${this.limit}`)
        return
      }

      const tmp = JSON.parse(JSON.stringify(this.valueVModel))
      tmp.push({ [this.filed.start]: undefined, [this.filed.end]: undefined })
      this.$emit('input', tmp)
    },
    // 事件 - 删除条目
    onDeleteItem (index) {
      const tmp = JSON.parse(JSON.stringify(this.valueVModel))
      tmp.splice(index, 1)
      this.$emit('input', tmp)
    }
  },
}
</script>

<style lang="scss" scoped>
  .age-limit-item {
    display: flex;
    align-items: center;
    margin-bottom: 5px;
    justify-content: space-between;
    .separator {
      margin: 0 20px;
    }
  }
</style>
